//
//  simShopDetailController.m
//  simens
//
//  Created by amy zhang on 12-7-16.
//  Copyright (c) 2012年 yst. All rights reserved.
//

#import "simShopDetailController.h"
#import "ASIHTTPRequest.h"
#import "JSONKit.h"
#import "simProjectViewController.h"
#import "simAddVisitInfoController.h"
#import "ASIFormDataRequest.h"

@implementation deviceItem

@synthesize name,status,dev_id,sta_id,date,contactor,phone,opptyid;

@end
@implementation dictItem
@synthesize itemid,itemname;

@end

@interface simShopDetailController ()<UITableViewDelegate, UITableViewDataSource,UIPickerViewDelegate, UIPickerViewDataSource,UITextViewDelegate,ASIHTTPRequestDelegate>

@property (nonatomic,strong) UITableView *shopTableView;
@property (nonatomic,strong) UIPickerView *myPickerView;
@property (nonatomic,strong) NSMutableArray *devicePickerArray;
@property (nonatomic,strong) NSMutableArray *statusPickerArray;
@property (nonatomic,strong) NSMutableArray *deviceVisitArray;
@property (nonatomic,strong) UIButton *addButton;
@property (nonatomic,strong) UIButton *confirmButton;
@property (nonatomic,strong) visitorItem* customer;
@property (nonatomic,strong) UITextView *reportTextField;
@property (nonatomic,strong) UITextView *shareTextField;
@property (nonatomic,strong) NSMutableArray *lastVisitArray;
@property (nonatomic,strong) ASIHTTPRequest *lastvisitRequest;
@property (nonatomic,strong) ASIFormDataRequest *submitnewRequest;
@property (nonatomic,strong) UIAlertView *submitOkAlert;
@property (nonatomic,strong) NSString *visitType;
@property (nonatomic,strong) deviceItem *selecteditem;

@end

@implementation simShopDetailController

@synthesize shopTableView=_shopTableView;
@synthesize addButton=_addButton;
@synthesize confirmButton=_confirmButton;
@synthesize customer=_customer;
@synthesize reportTextField=_reportTextField;
@synthesize shareTextField=_shareTextField;
@synthesize lastVisitArray=_lastVisitArray;
@synthesize lastvisitRequest=_lastvisitRequest;
@synthesize submitnewRequest=_submitnewRequest;
@synthesize submitOkAlert=_submitOkAlert;
@synthesize visitType=_visitType;
@synthesize deviceVisitArray=_deviceVisitArray;
@synthesize selecteditem=_selecteditem;
@synthesize myPickerView,devicePickerArray,statusPickerArray;
@synthesize detailDelegate=_detailDelegate;

- (void)viewDidLoad
{
    //NSLog(@"viewDidLoad");
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.title=@"客户拜访";
    
    self.visitType=@"1";//项目跟进
    
    self.deviceVisitArray=[[NSMutableArray alloc] init];
    devicePickerArray=[[NSMutableArray alloc] init];
    statusPickerArray= [[NSMutableArray alloc] init];
    self.lastVisitArray=[[NSMutableArray alloc] init];
    
    [self showMbprogress];
    NSString *u=[NSString stringWithFormat:@"%@/getSiemensCustProStatus?custDetailId=%@&mobilePhone=%@&pwd=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],self.customer.custId,[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginMobile"],[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginPassword"]];
    NSLog(@"request url is:%@",u);
    NSURL *url = [NSURL URLWithString:u];
    self.lastvisitRequest = [ASIHTTPRequest requestWithURL:url];
    [self.lastvisitRequest setDelegate:self];
    [self.lastvisitRequest start];
       
    
    self.shopTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 
                                                                         self.view.bounds.size.height) 
                                                        style:UITableViewStyleGrouped];  
    
    [self.shopTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.shopTableView setDelegate:self];
    [self.shopTableView setDataSource:self];
    [self.shopTableView setEditing:NO animated:YES];
    [self.view addSubview: self.shopTableView];
    
    
//    NSArray * dictArray=[self requestFordata:@"getSiemensDict?dictTypeValue=pro@siemens" objecName:@"siemensPro"];
//    if(dictArray!=nil){
//        
//        for(int i=0;i<dictArray.count;i++){
//        NSDictionary* temp = [dictArray objectAtIndex:i];
//        dictItem *d=[[dictItem alloc] init];
//        d.itemname=[temp objectForKey:@"itemName"];
//        d.itemid=[temp objectForKey:@"itemId"];
//        [devicePickerArray addObject:d];
//       }
//    }
//    
//    NSArray * statusArray=[self requestFordata:@"getSiemensDict?dictTypeValue=prostatus@siemens" objecName:@"siemensPro"];
//    if(statusArray!=nil){
//        
//        for(int i=0;i<statusArray.count;i++){
//            NSDictionary* temp = [statusArray objectAtIndex:i];
//            dictItem *d=[[dictItem alloc] init];
//            d.itemname=[temp objectForKey:@"itemName"];
//            d.itemid=[temp objectForKey:@"itemId"];
//            [statusPickerArray addObject:d];
//        }
//    }
    
    myPickerView=[[UIPickerView alloc] initWithFrame:CGRectZero];
    myPickerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    CGSize pickerSize = [myPickerView sizeThatFits:CGSizeZero];
    myPickerView.frame = [self pickerFrameWithSize:pickerSize];
    
    myPickerView.showsSelectionIndicator = YES;	// note this is default to NO
    
    // this view controller is the data source and delegate
    myPickerView.delegate = self;
    myPickerView.dataSource = self;
    myPickerView.hidden=YES;
    [self.view addSubview:myPickerView];

    UIBarButtonItem* tempRight = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(submitVisitInfo)];
    self.navigationItem.rightBarButtonItem = tempRight;
    
    
}

-(NSArray*) requestFordata:(NSString*) methodNameWithParameter objecName:(NSString*) name{
    
    NSString* u=[NSString stringWithFormat:@"%@/%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],methodNameWithParameter];    
    NSURL *url = [NSURL URLWithString:u];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    NSError *error = [request error];
    
    if (!error) {
        NSString *response = [request responseString];
        NSLog(@"%@ load data is :%@",methodNameWithParameter,response);
        NSDictionary* dict = [response objectFromJSONString];
        NSArray * dictArray=[dict objectForKey:name];
        return dictArray;
        
    }
    return nil;
}

-(void) setCustomerItem:(visitorItem*) customer{
    //NSLog(@"setCustomerItem");
    self.customer=customer;
}
-(void) setdeviceItem:(deviceItem *)visitdevice{
    if (visitdevice!=nil) {
        [self.deviceVisitArray addObject:visitdevice];
        //NSLog(@"devicearray is %d",self.deviceVisitArray.count);
    }
}
-(void)viewWillAppear:(BOOL)animated{
    // NSLog(@"viewWillAppear");
    [self.shopTableView reloadData];
    
    [super viewWillAppear:animated];
}

-(void)viewDidAppear:(BOOL)animated{
//[self.myPickerView reloadComponent:0];
   // NSLog(@"viewDidAppear");
    [super viewDidAppear:animated];
}

-(void) submitVisitInfo {
    Boolean a=FALSE;
    if([self.visitType isEqualToString:@"0"]){
        a=TRUE;
    }else 
    if(self.deviceVisitArray.count>0){
        a=TRUE;
    }
    else if([self.shareTextField.text isEqualToString:@""]==NO){
        a=TRUE;
    }
    else if([self.reportTextField.text isEqualToString:@""]==NO){
        a=TRUE;
    }
    
    if(a==FALSE){
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:@"请维护拜访信息" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }else{
    
    [self showMbprogress];
    NSString* u=[NSString stringWithFormat:@"%@/%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],@"insertSiemensUpLoad"];
    NSURL *url = [NSURL URLWithString:u];
    
    self.submitnewRequest = [ASIFormDataRequest requestWithURL:url];
    [self.submitnewRequest addPostValue: self.reportTextField.text forKey:@"report"];
    //detail 格式：项目id/状态ID/opptyid/联系人=联系方式;联系人=联方式&项目id/状态ID/opptyid/联系人=联系方式;联系人=联方式
    NSMutableString *detailString=[[NSMutableString alloc] init];
    for(deviceItem* item in self.deviceVisitArray){
        NSString *s=[NSString stringWithFormat:@"%@/%@/%@/%@=%@",item.dev_id,item.sta_id,item.opptyid,item.contactor,item.phone];
        [detailString appendString:s];
        [detailString appendString:@"&"];
    }
    NSLog(@"detail:%@ share:%@ reprot:%@ line:%@ custid:%@ type:%@",detailString,self.shareTextField.text,self.reportTextField.text,self.customer.datelineId,self.customer.custId,self.visitType);
    [self.submitnewRequest addPostValue: detailString forKey:@"detail"];
    [self.submitnewRequest addPostValue: self.shareTextField.text forKey:@"share"];
    [self.submitnewRequest addPostValue: self.customer.datelineId forKey:@"datelineId"];
    [self.submitnewRequest addPostValue: self.customer.custId forKey:@"detailCustId"];
    [self.submitnewRequest addPostValue: self.visitType forKey:@"type"]; //0回访 1项目跟进
    [self.submitnewRequest addPostValue: [[NSUserDefaults standardUserDefaults]objectForKey:@"LoginMobile"] forKey:@"mobile"];
    [self.submitnewRequest addPostValue: [[NSUserDefaults standardUserDefaults]objectForKey:@"LoginPassword"] forKey:@"pwd"];
        
    [self.submitnewRequest setDelegate:self];
    [self.submitnewRequest start];
    
   }

}

- (void)requestFinished:(ASIHTTPRequest *)request {
    //NSLog(@"requestFinished");
    NSError *error = [request error];
    
    if (!error) {
        NSString *response = [request responseString];
        
        if(request==self.lastvisitRequest){
            
            NSLog(@"load data is :%@",response);
            NSDictionary* dict = [response objectFromJSONString];
            NSArray * dictArray=[dict objectForKey:@"siemensCustomer"];
            if(dictArray!=nil){
                for (int i=0;i<dictArray.count; i++) {
                    NSDictionary* temp = [dictArray objectAtIndex:i];
                    deviceItem *v=[[deviceItem alloc] init];
                    v.name=[temp objectForKey:@"proType"];
                    v.status=[temp objectForKey:@"proStatus"];
                    v.date=[temp objectForKey:@"visitDate"];
                    v.contactor=[temp objectForKey:@"proContact"];
                    if([[temp objectForKey:@"proContactTel"] isKindOfClass:[NSString class]]==YES){
                        v.phone=[temp objectForKey:@"proContactTel"];
                    }else{
                    v.phone=[[temp objectForKey:@"proContactTel"] stringValue];
                    }
                    v.dev_id=[[temp objectForKey:@"proId"] stringValue];
                    v.sta_id=[[temp objectForKey:@"proStatusId"] stringValue];
                    [self.lastVisitArray addObject:v];
                    
                }
                [self.shopTableView reloadData];
            }
            [self hideMbProgress];
            
        }else if(request==self.submitnewRequest){
            NSString *result;
            
            if ([response isEqualToString:@"false"]) {
                result = @"操作失败，请稍后再试";
                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" message:result delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
                [self hideMbProgress];
                [alert show];
            } else {
                result = @"操作成功";
                self.submitOkAlert = [[UIAlertView alloc] initWithTitle:@"" message:result delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
                [self hideMbProgress];
                [self.submitOkAlert show];
                
            }
        }
        
        
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request {
    [self hideMbProgress];
}

-(void) alertView: (UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(actionSheet==self.submitOkAlert){
        if(buttonIndex==0){
            if (self.detailDelegate) {
                [self.detailDelegate SubmitVisitSuccess];
            }
                
         [self.navigationController popViewControllerAnimated:YES];
        
        }
        
    }
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  //  NSLog(@"numberOfSectionsInTableView");
    return 5;
}// Default is 1 if not implemented


//tableview行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  //  NSLog(@"numberOfRowsInSection section is:%d",section);
    if (section == 2) {
        return [self.lastVisitArray count];
    }else if (section == 1) {
        return [self.deviceVisitArray count];
    }
    else {
        return 1;
    }
    
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
   // NSLog(@"cellForRowAtIndexPath section=%d row=%d",indexPath.section,indexPath.row);
    
    NSString* CellIdentifier = [NSString stringWithFormat:@"%d%d",indexPath.section, indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    } 
    
    for (UIView *v in [cell subviews]) {
        if ([v isKindOfClass:[UILabel class]] |
            [v isKindOfClass:[UIButton class]]|
            [v isKindOfClass:[UITextView class]] |
            [v isKindOfClass:[UIImageView class]] ) {
            [v removeFromSuperview];
        }
    }
    
    if (indexPath.section==0) {
        
        UIImage *logo=[UIImage imageNamed:@"hospital_logo.png"];
        UIImageView *logoView=[[UIImageView alloc] initWithImage:logo];
        [logoView setFrame:CGRectMake(15, 2, 100, 98)];
        [cell addSubview:logoView];
        
        UILabel* shopnameLabel = [[UILabel alloc] initWithFrame:CGRectMake(115, 5, 195, 50)];
        [shopnameLabel setBackgroundColor:[UIColor clearColor]];
        [shopnameLabel setText:self.customer.custNameEn]; 
        shopnameLabel.font=[UIFont systemFontOfSize:16];
        shopnameLabel.numberOfLines=2;
        [cell addSubview:shopnameLabel];
        
        UILabel* contactnameLabel = [[UILabel alloc] initWithFrame:CGRectMake(115, 55, 195, 20)];
        [contactnameLabel setBackgroundColor:[UIColor clearColor]];
        [contactnameLabel setText:[NSString stringWithFormat:@"联系人：%@", self.customer.contactName == nil ? @"" : self.customer.contactName]];
        [contactnameLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
        contactnameLabel.font=[UIFont systemFontOfSize:15];
        [cell addSubview:contactnameLabel];
        
        UILabel* contactphoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(115, 75, 155, 20)];
        [contactphoneLabel setBackgroundColor:[UIColor clearColor]];
        [contactphoneLabel setText:[NSString stringWithFormat:@"电话：%@", self.customer.contactPhone == nil ? @"" : self.customer.contactPhone]];
        [contactphoneLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
        contactphoneLabel.font=[UIFont systemFontOfSize:15];
        [cell addSubview:contactphoneLabel];
        
        UIButton* phoneBt=[UIButton buttonWithType:UIButtonTypeCustom];
        [phoneBt setFrame:CGRectMake(270, 75, 30, 20)];
        [phoneBt setBackgroundColor:[UIColor clearColor]];
        [phoneBt setTitle:self.customer.contactPhone forState:UIControlStateNormal];
        [phoneBt setImage:[UIImage imageNamed:@"phone.png"] forState:UIControlStateNormal];
        //定义点击时的响应函数
        [phoneBt addTarget:self action:@selector(phoneCallbuttonPress:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:phoneBt];
        
        
    }else if(indexPath.section==2){//上次拜访项目
        
        deviceItem *item=[self.lastVisitArray objectAtIndex:indexPath.row];
        
        UILabel* devicenameLabel =[[UILabel alloc] initWithFrame:CGRectMake(20, 5, 290, 25)];
        [devicenameLabel setBackgroundColor:[UIColor clearColor]];        
        [devicenameLabel setText: [NSString stringWithFormat:@"项目:%@",item.name]]; 
        devicenameLabel.font=[UIFont systemFontOfSize:16];
        [cell addSubview:devicenameLabel];
        
        UILabel* statusLabel =[[UILabel alloc] initWithFrame:CGRectMake(20, 30, 290, 25)];
        [statusLabel setBackgroundColor:[UIColor clearColor]];        
        [statusLabel setText:[NSString stringWithFormat:@"项目状态:%@",item.status]]; 
        statusLabel.font=[UIFont systemFontOfSize:16];
        [cell addSubview:statusLabel];
        
        UILabel* contactLabel =[[UILabel alloc] initWithFrame:CGRectMake(20, 55, 130, 25)];
        [contactLabel setBackgroundColor:[UIColor clearColor]];        
        [contactLabel setText: [NSString stringWithFormat:@"联系人:%@",item.contactor]]; 
        contactLabel.font=[UIFont systemFontOfSize:16];
        [cell addSubview:contactLabel];
        
        UILabel* phoneLabel =[[UILabel alloc] initWithFrame:CGRectMake(20, 80, 160, 25)];
        [phoneLabel setBackgroundColor:[UIColor clearColor]];        
        [phoneLabel setText:[NSString stringWithFormat:@"电话:%@",item.phone]]; 
        phoneLabel.font=[UIFont systemFontOfSize:16];
        [cell addSubview:phoneLabel];
        
        UIButton* phoneBt=[UIButton buttonWithType:UIButtonTypeCustom];
        [phoneBt setFrame:CGRectMake(180, 80, 30, 25)];
        [phoneBt setBackgroundColor:[UIColor clearColor]];
        [phoneBt setTitle:item.phone forState:UIControlStateNormal];
        [phoneBt setImage:[UIImage imageNamed:@"phone.png"] forState:UIControlStateNormal];
        //定义点击时的响应函数
        [phoneBt addTarget:self action:@selector(phoneCallbuttonPress:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:phoneBt];
        
        UILabel* dateLabel =[[UILabel alloc] initWithFrame:CGRectMake(20, 105, 290, 25)];
        [dateLabel setBackgroundColor:[UIColor clearColor]];        
        [dateLabel setText:[NSString stringWithFormat:@"拜访时间:%@",item.date]]; 
        dateLabel.font=[UIFont systemFontOfSize:16];
        [cell addSubview:dateLabel];
        
    }else if (indexPath.section==1) {//本次提交项目
       
        deviceItem *item=[self.deviceVisitArray objectAtIndex:indexPath.row];
        
        UILabel* devicenameLabel =[[UILabel alloc] initWithFrame:CGRectMake(20, 5, 290, 25)];
        [devicenameLabel setBackgroundColor:[UIColor clearColor]];        
        [devicenameLabel setText: [NSString stringWithFormat:@"项目:%@",item.name]]; 
        devicenameLabel.font=[UIFont systemFontOfSize:16];
        [cell addSubview:devicenameLabel];
        
        UILabel* statusLabel =[[UILabel alloc] initWithFrame:CGRectMake(20, 30, 290, 25)];
        [statusLabel setBackgroundColor:[UIColor clearColor]];        
        [statusLabel setText:[NSString stringWithFormat:@"项目状态:%@",item.status]]; 
        statusLabel.font=[UIFont systemFontOfSize:16];
        [cell addSubview:statusLabel];
        
        UILabel* contactLabel =[[UILabel alloc] initWithFrame:CGRectMake(20, 55, 130, 25)];
        [contactLabel setBackgroundColor:[UIColor clearColor]];        
        [contactLabel setText: [NSString stringWithFormat:@"联系人:%@",item.contactor]]; 
        contactLabel.font=[UIFont systemFontOfSize:16];
        [cell addSubview:contactLabel];
        
        UILabel* phoneLabel =[[UILabel alloc] initWithFrame:CGRectMake(150, 55, 160, 25)];
        [phoneLabel setBackgroundColor:[UIColor clearColor]];        
        [phoneLabel setText:[NSString stringWithFormat:@"电话:%@",item.phone]]; 
        phoneLabel.font=[UIFont systemFontOfSize:16];
        [cell addSubview:phoneLabel];
        
        UILabel* OPPTYIDLabel =[[UILabel alloc] initWithFrame:CGRectMake(20, 80, 290, 25)];
        [OPPTYIDLabel setBackgroundColor:[UIColor clearColor]];        
        [OPPTYIDLabel setText: [NSString stringWithFormat:@"OPPTYID:%@", item.opptyid == nil ? @"" : item.opptyid]];
        OPPTYIDLabel.font=[UIFont systemFontOfSize:16];
        [cell addSubview:OPPTYIDLabel];
    }else if(indexPath.section==3){//汇报
        self.reportTextField = [[UITextView alloc] initWithFrame:CGRectMake(10, 0, 300, 60)];  
        [self.reportTextField setScrollEnabled:YES];
        [self.reportTextField setDelegate:self];
        self.reportTextField.backgroundColor=[UIColor clearColor];
        self.reportTextField.returnKeyType=UIReturnKeyDone;
        [cell addSubview:self.reportTextField];
    }else if(indexPath.section==4){//分享
        self.shareTextField=[[UITextView alloc ] initWithFrame:CGRectMake(10, 0, 300, 60)];
        [self.shareTextField setScrollEnabled:YES];
        [self.shareTextField setDelegate:self];
        self.shareTextField.backgroundColor=[UIColor clearColor];
        self.shareTextField.returnKeyType=UIReturnKeyDone;
        //self.shareTextField.font=[UIFont fontWithName:@"Arial" size:15.0];
        
        [cell addSubview:self.shareTextField];
        
    }
    
    return cell;
    
}

//row高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    //NSLog(@"heightForRowAtIndexPath section=%d row=%d",indexPath.section,indexPath.row);
    if (indexPath.section==0) {
        return 100;
    }else if(indexPath.section==1){
        return 105; 
    }else if(indexPath.section==2) {
        return 130;
    }
    else if(indexPath.section==3) {
        return 60;
    }
    else if(indexPath.section==4) {
        return 60;
    }
    
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    // NSLog(@"heightForHeaderInSection section=%d",section);
    if(section==0){
        return 0;
    }else if(section==1){
        return 30;
    }else if(section==2){
            return 30;
    }
    return 20;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
   // NSLog(@"heightForFooterInSection section=%d",section);
    if(section==4){
        return 100;
    }
    return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
 //   NSLog(@"titleForHeaderInSection section=%d",section);
    if(section==0){
        //return @"客户信息";
    }else if (section == 1) {
        return @"本次拜访项目";
    }else if(section==2){
            return @"上次拜访项目";
    }else if(section==3){
        return @"汇报";
    }else if(section==4){
        return @"分享";
    }
    return @"";
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
   // NSLog(@"canEditRowAtIndexPath section=%d row=%d",indexPath.section,indexPath.row);
    if(indexPath.section==1){
        return YES;
    }
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
  //  NSLog(@"commitEditingStyle section=%d row=%d",indexPath.section,indexPath.row);
    if(editingStyle==UITableViewCellEditingStyleDelete){
        if(indexPath.section==1)
        [self.deviceVisitArray removeObjectAtIndex:indexPath.row];
        [self.shopTableView reloadData];
    }
    
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
  //  NSLog(@"viewForHeaderInSection section=%d",section);
    if (section==1) {
         UIView* tempView = [[UIView alloc] init];
        
        UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(20, 0, 80, 30)];
        [label setBackgroundColor:[UIColor clearColor]];
        [label setText:@"项目跟进"];
        [tempView addSubview:label];
        
        CGRect frame = CGRectMake(110.0, 0, 94.0, 27.0);
        UISwitch *switchCtl = [[UISwitch alloc] initWithFrame:frame];
        [switchCtl addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        
        // in case the parent view draws with a custom color or gradient, use a transparent color
        switchCtl.backgroundColor = [UIColor clearColor];
        [switchCtl setOn:YES];
        [tempView addSubview:switchCtl];
        
        self.addButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
        [self.addButton setFrame:CGRectMake(260, 0, 50, 30)];
        [self.addButton setBackgroundColor:[UIColor clearColor]];
        //定义点击时的响应函数
        [self.addButton addTarget:self action:@selector(addbuttonPress) forControlEvents:UIControlEventTouchUpInside];
        [tempView addSubview:self.addButton];
        
        self.confirmButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [self.confirmButton setFrame:CGRectMake(260, 5, 50, 25)];
        [self.confirmButton setBackgroundColor:[UIColor clearColor]];
        [self.confirmButton setTitle:@"确定" forState:UIControlStateNormal];
        //定义点击时的响应函数
        [self.confirmButton addTarget:self action:@selector(confirmbuttonPress) forControlEvents:UIControlEventTouchUpInside];
        [tempView addSubview:self.confirmButton];
        self.confirmButton.hidden=YES;

        return tempView;

        
          }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    if(indexPath.section==1){
//        simProjectViewController *projectController=[[simProjectViewController alloc] init];
//        [projectController setitems:self.customer.datelineId];
//        [self.navigationController pushViewController:projectController animated:YES];
//    }
}
- (void)switchAction:(id)sender
{
	 NSLog(@"switchAction: value = %d", [sender isOn]);
    if([sender isOn]){
        self.addButton.hidden=NO;
        self.visitType=@"1";
    }else{
        self.addButton.hidden=YES;
        self.visitType=@"0";
    }
}
-(void) addbuttonPress{
    
//    myPickerView.hidden=NO;
//    self.confirmButton.hidden=NO;
//     self.addButton.hidden=YES;
    //NSLog(@"press addbutton");
    
    simAddVisitInfoController *addController=[[simAddVisitInfoController alloc] init];
    [addController  setLastVisitDevice:self.lastVisitArray];
    [self.navigationController pushViewController:addController animated:YES];
    
}

-(void) confirmbuttonPress{
     //NSLog(@"press confirmbutton");
    
    myPickerView.hidden=YES;
    if (self.selecteditem!=nil) {
        [self.deviceVisitArray addObject:self.selecteditem];
        [self.shopTableView reloadData];
    }

    self.confirmButton.hidden=YES;
    self.addButton.hidden=NO;
}

-(void)phoneCallbuttonPress:(UIButton*) bt{
    NSLog(@"call phone is %@",bt.currentTitle);//将手机号码作为标题传参
    NSString* number = [NSString stringWithFormat:@"tel://%@",bt.currentTitle];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:number]];
    
//    UIWebView *callPhoneWebVw = [[UIWebView alloc] init];  
//    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:number]];  
//    [callPhoneWebVw loadRequest:request]; 
}



// return the picker frame based on its size, positioned at the bottom of the page
- (CGRect)pickerFrameWithSize:(CGSize)size
{
	CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
	CGRect pickerRect = CGRectMake(	0.0,
                                   screenRect.size.height - 42.0 - size.height,
                                   size.width,
                                   size.height);
	return pickerRect;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	
    dictItem* dev=[devicePickerArray objectAtIndex:[pickerView selectedRowInComponent:0]];
    dictItem* sta=[statusPickerArray objectAtIndex:[pickerView selectedRowInComponent:1]];
		// report the selection to the UI label
        NSLog(@"%@  %@- %@  %@",dev.itemid,dev.itemname,sta.itemid, sta.itemname);
    self.selecteditem=[[deviceItem alloc] init];
    self.selecteditem.name=dev.itemname;
    self.selecteditem.status=sta.itemname;
    self.selecteditem.dev_id=dev.itemid;
    self.selecteditem.sta_id=sta.itemid;
	
}


#pragma mark -
#pragma mark UIPickerViewDataSource

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	NSString *returnStr = @"";	
	// note: custom picker doesn't care about titles, it uses custom views
	
		if (component == 0)
		{
			dictItem* dev = [devicePickerArray objectAtIndex:row];
            returnStr=dev.itemname;
		}
		else
		{
			dictItem* sta = [statusPickerArray objectAtIndex:row];
            returnStr=sta.itemname;
		}
	
	return returnStr;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	CGFloat componentWidth = 0.0;
    
	if (component == 0)
		componentWidth = 200.0;	// first column size is wider to hold names
	else
		componentWidth = 80.0;	// second column is narrower to show numbers
    
	return componentWidth;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
	return 40.0;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(component==0){
        return [devicePickerArray count];
    }else if(component==1){
        return [statusPickerArray count];  
    }
	return 0;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 2;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



- (void)textViewDidBeginEditing:(UITextView *)textView{
    //NSLog(@"textview did begin editing");
     //键盘遮住了文本字段，视图整体上移
    
    [UIView beginAnimations:nil context:nil]; // begins animation block
    [UIView setAnimationDuration:0.5];        // sets animation duration
    
    CGRect frame = self.view.frame;  
    frame.origin.y -=216;  
    frame.size.height +=216;  
    self.view.frame = frame; 
    
    [UIView commitAnimations];   // commits the animation block.  This Block is done.
    
}

-(void)textViewDidEndEditing:(UITextView *)textView{
    //NSLog(@"textview did end editing");

    [UIView beginAnimations:nil context:nil]; // begins animation block
    [UIView setAnimationDuration:0.5];        // sets animation duration
    //之前视图上移了  现在移回来 
      CGRect frame = self.view.frame;  
       frame.origin.y +=216;  
       frame.size.height -=216;  
       self.view.frame = frame;    
    
    [UIView commitAnimations];   // commits the animation block.  This Block is done.
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.shareTextField resignFirstResponder];
    [self.reportTextField resignFirstResponder];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

@end
